package cd.cdyb.sms.service.impl;

import cd.cdyb.sms.dao.CompanyDao;
import cd.cdyb.sms.dao.MessageRecordingDao;
import cd.cdyb.sms.dao.TemplateDao;
import cd.cdyb.sms.domain.MessageRecording;
import cd.cdyb.sms.dto.MessageCarrier;
import cd.cdyb.sms.dto.MessageRecordingDto;
import cd.cdyb.sms.dto.MessageRecordingStatisticsDto;
import cd.cdyb.sms.dto.PageResult;
import cd.cdyb.sms.dto.expand.ExCompanyDto;
import cd.cdyb.sms.dto.query.MessageRecordingQueryDto;
import cd.cdyb.sms.service.CompanyService;
import cd.cdyb.sms.service.MessageRecordingService;
import cd.cdyb.sms.utils.BeanUtilPlus;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service("messageRecordingService")
public class MessageRecordingServiceImpl implements MessageRecordingService {


    @Resource
    private CompanyDao companyDao;

    @Resource
    private TemplateDao templateDao;

    @Resource
    private MessageRecordingDao messageRecordingDao;

    @Resource
    private CompanyService companyService;

    @Override
    public void insertMessageRecording(MessageCarrier messageCarrier) {
        ExCompanyDto cacheCompanyByKey = companyService.getCacheCompanyByKey(messageCarrier.getCompanyKey());
        MessageRecording messageRecording = new MessageRecording();
        messageRecording.setCompanyId(cacheCompanyByKey.getCompanyId());
        messageRecording.setCompanyName(cacheCompanyByKey.getCompanyName());
        messageRecording.setType(messageCarrier.getType());
        messageRecording.setPhone(messageCarrier.getPhone());

        messageRecording.setContent(messageCarrier.getContent());
        if (StringUtils.isNotBlank(messageCarrier.getFailReason())){
            messageRecording.setFailReason(messageCarrier.getFailReason());
            messageRecording.setStatus(2);
        } else {
            messageRecording.setStatus(0);
        }
        messageRecording.setUseCount(messageCarrier.getUseCount());
        messageRecording.setWordLength(messageCarrier.getContent().length());
        messageRecording.setTaskNo(messageCarrier.getTaskNo());
        String number = IdUtil.getSnowflake().nextIdStr();
        messageRecording.setNumber(number);
        messageRecording.setCompanyKey(messageCarrier.getCompanyKey());
        messageRecording.setTemplateNumber(messageCarrier.getTemplateId());
        messageRecordingDao.insert(messageRecording);
    }

    @Override
    public Map<String, Object> messageRecordingStatisticsPageWithClient(MessageRecordingQueryDto messageRecordingQueryDto) {
        Map<String, Object> map = new HashMap<>(16);
        Page<MessageRecordingStatisticsDto> messageRecordingStatisticsDtoPage = getMessageRecordingStatisticsDtoPage(messageRecordingQueryDto);
        PageResult<MessageRecordingStatisticsDto> pageResult = new PageResult<>(messageRecordingQueryDto.getPageNo(), messageRecordingQueryDto.getPageSize(), messageRecordingStatisticsDtoPage.getRecords(), messageRecordingStatisticsDtoPage.getTotal());
        //查询总数
        MessageRecordingStatisticsDto messageRecordingStatisticsDto = messageRecordingDao.messageRecordingStatistics(messageRecordingQueryDto);
        map.put("page", pageResult);
        map.put("statistics", messageRecordingStatisticsDto);
        return map;
    }

    @Override
    public PageResult<MessageRecordingDto> messageRecordingPageWithClient(MessageRecordingQueryDto messageRecordingQueryDto) {
        LambdaQueryWrapper<MessageRecording> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(MessageRecording::getPhone, MessageRecording::getCreateTime, MessageRecording::getType,
                MessageRecording::getContent, MessageRecording::getUseCount, MessageRecording::getStatus, MessageRecording::getFailReason, MessageRecording::getWordLength, MessageRecording::getCompanyName, MessageRecording::getTemplateNumber, MessageRecording::getUseCount);
        if (Objects.nonNull(messageRecordingQueryDto.getCompanyId())) {
            wrapper.eq(MessageRecording::getCompanyId, messageRecordingQueryDto.getCompanyId());
        }
        if (StringUtils.isNotBlank(messageRecordingQueryDto.getPhone())) {
            wrapper.eq(MessageRecording::getPhone, messageRecordingQueryDto.getPhone());
        }
        if (StringUtils.isNotBlank(messageRecordingQueryDto.getTemplateNumber())) {
            wrapper.eq(MessageRecording::getTemplateNumber, messageRecordingQueryDto.getTemplateNumber());
        }
        if (messageRecordingQueryDto.getStatus() != null) {
            wrapper.eq(MessageRecording::getStatus, messageRecordingQueryDto.getStatus());
        }
        if (Objects.nonNull(messageRecordingQueryDto.getStartTime()) && Objects.nonNull(messageRecordingQueryDto.getEndTime())) {
            wrapper.between(MessageRecording::getCreateTime, messageRecordingQueryDto.getStartTime(), messageRecordingQueryDto.getEndTime());
        }
        wrapper.orderByDesc(MessageRecording::getCreateTime);
        Page<MessageRecording> page = new Page<>(messageRecordingQueryDto.getPageNo(), messageRecordingQueryDto.getPageSize());
        Page<MessageRecording> messageRecordingPage = messageRecordingDao.selectPage(page, wrapper);
        List<MessageRecording> records = messageRecordingPage.getRecords();
        List<MessageRecordingDto> messageRecordingDtoList = BeanUtilPlus.copyAs(records, MessageRecordingDto.class);
        return new PageResult<>(messageRecordingQueryDto.getPageNo(), messageRecordingQueryDto.getPageSize(), messageRecordingDtoList, messageRecordingPage.getTotal());
    }

    @Override
    public MessageRecordingStatisticsDto indexStatistics(MessageRecordingQueryDto messageRecordingQueryDto) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate currentDate = LocalDate.now();
        LocalDate firstDayOfMonth = currentDate.withDayOfMonth(1);
        LocalDate lastDayOfMonth = currentDate.withDayOfMonth(currentDate.lengthOfMonth());
        messageRecordingQueryDto.setStartDateWithTime(formatter.format(firstDayOfMonth.atStartOfDay()));
        messageRecordingQueryDto.setEndDateWithTime(formatter.format(lastDayOfMonth.atTime(LocalTime.MAX)));
        return messageRecordingDao.messageRecordingStatistics(messageRecordingQueryDto);
    }


    private Page<MessageRecordingStatisticsDto> getMessageRecordingStatisticsDtoPage(MessageRecordingQueryDto messageRecordingQueryDto) {
        Page<MessageRecordingStatisticsDto> page = new Page<>(messageRecordingQueryDto.getPageNo(), messageRecordingQueryDto.getPageSize());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        messageRecordingQueryDto.setStartDateWithTime(formatter.format(messageRecordingQueryDto.getStartDate().atStartOfDay()));
        messageRecordingQueryDto.setEndDateWithTime(formatter.format(messageRecordingQueryDto.getEndDate().atTime(LocalTime.MAX)));
        return messageRecordingDao.messageRecordingStatisticsPage(messageRecordingQueryDto, page);
    }

    public static List<LocalDate> getDateList(LocalDate startDate, LocalDate endDate) {
        List<LocalDate> dateList = new ArrayList<>();
        for (LocalDate date = startDate; date.isBefore(endDate.plusDays(1)); date = date.plusDays(1)) {
            dateList.add(date);
        }
        return dateList;
    }
}
